#include "HardwareUsartInterface.h"


/*
HardwareUsartInterface::HardwareUsartInterface(){}
HardwareUsartInterface::HardwareUsartInterface(HardwareUsart& u){}

void HardwareUsartInterface::write(void* data, unsigned long int length){}
void HardwareUsartInterface::writeByte(unsigned char data){}
unsigned char HardwareUsartInterface::readByte(){return 0;}
void* HardwareUsartInterface::read(unsigned long int length){return 0;}
unsigned char HardwareUsartInterface::full(){return 0;}
unsigned char HardwareUsartInterface::empty(){return 0;}
void HardwareUsartInterface::sendInput(){}
void HardwareUsartInterface::receiveOutput(){}
void HardwareUsartInterface::run(){}
void HardwareUsartInterface::config(){}
*/


HardwareUsartInterface::HardwareUsartInterface()
{}

HardwareUsartInterface::HardwareUsartInterface(HardwareUsart& u)
{
	usart = u;
	input = Queue<unsigned char>();
	output = Queue<unsigned char>();
}

unsigned char HardwareUsartInterface::full()
{
	return 0; //never full
}
unsigned char HardwareUsartInterface::empty()
{
	return output.empty(); //can be empty though.
}

void HardwareUsartInterface::write(void* data, unsigned long int length)
{
	unsigned char* pointer = (unsigned char*) data;
	int i = 0;
	for(i = 0; i < length; i++)
	{
		unsigned char copy = pointer[i];
		input.push(copy);
	}
}

void HardwareUsartInterface::writeByte(unsigned char data)
{
	input.push(data);
}

unsigned char HardwareUsartInterface::readByte()
{
	unsigned char data = 0;
	if(output.empty()!=1)
		data = output.pop();
	return data;
}

void* HardwareUsartInterface::read(unsigned long int length)
{
	void* data = (void*) malloc(length*sizeof(unsigned char));
	unsigned char* data2 = (unsigned char*) data;
	int i = 0;
	for(i = 0; i < length; i++)
	{
		if(output.empty() != 1)
			data2[i] = output.pop();
	}
	data = (void*) data2;
	return data;
}


void HardwareUsartInterface::run()
{

	if(usart.getFinished()==1)
	{
		//get the new output data
		output.push(usart.get());
		if(input.empty()!=1)
			usart.set(input.pop());
		
	}
	if(usart.config.polling==1)
		usart.run();

}

void HardwareUsartInterface::receiveOutput()
{

	unsigned char value = usart.getReceivedData();
	output.push(value); //adds the received value to the queue.

}

void HardwareUsartInterface::sendInput()
{

	unsigned char value = 0xFF;
	if(input.empty()!=1)
		value = input.pop(); //gets the input from the queue.
	usart.setTransmitData(value);
	//usart.setTransmitter(1);


}

void HardwareUsartInterface::config(){}



